﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MODEL;
using System.IO;
using Newtonsoft.Json;

namespace Service.Main
{
    public class MainService : IMainService
    {
        public Task<List<MenuInfo>> GetMenuInfos()
        {
            return Task<List<MenuInfo>>.Run(() =>
                    {
                        if(!File.Exists("Configuration\\MenuConfiguration.json"))
                        {
                            return new List<MenuInfo>();
                        }
                        using (StreamReader sr = new StreamReader(File.OpenRead("Configuration\\MenuConfiguration.json")))
                        {                           
                            string json = sr.ReadToEnd();
                            List<MenuInfo> menuInfos = new List<MenuInfo>();
                            try
                            {
                                menuInfos = JsonConvert.DeserializeObject<List<MenuInfo>>(json);
                                menuInfos = menuInfos.Where(menu =>
                                {
                                    if (AppSetting.Instance.User == null || AppSetting.Instance.User.role == null)
                                    {
                                        return false;
                                    }

                                    if (string.IsNullOrEmpty(menu.AuthRoles))
                                    {
                                        return true;
                                    }

                                    string[] authList = menu.AuthRoles.Split(',');

                                    return authList.Contains(AppSetting.Instance.User.role.RoleSign, StringComparer.OrdinalIgnoreCase);
                                }).ToList();
                                return menuInfos;
                            }
                            catch
                            {
                                return menuInfos;
                            }
                        }                                               
                    });
        }
    }
}
